#include "myLib.h"

unsigned short *videoBuffer = (unsigned short *)0x6000000;

void drawImage4(int row, int col, int height, int width, const u16 *image)
{
	for(int r = 0; r<height; r++)
	{
		REG_DMA3SAD = (vu32)&image[(width*r)/2];
		REG_DMA3DAD = (vu32)&videoBuffer[OFFSET((row+r), col, SCREENWIDTH)/2];
		REG_DMA3CNT = (width/2) | DMA_ON;
	}
} 

void drawRect4(int row, int col, int height, int width, u8 index)
{
	volatile u16 color = index<<8 | index;
	int r;
	for(r=0; r<height; r++)
	{
		REG_DMA3SAD = (vu32)&color;
		REG_DMA3DAD = (vu32)&videoBuffer[OFFSET(row+r, col, 240)/2];
		REG_DMA3CNT = (width/2) | DMA_ON | DMA_SOURCE_FIXED;
	}
}

void waitForVblank()
{
	while(SCANLINECOUNTER > 160);
	while(SCANLINECOUNTER < 160);
}

void setPixel4(int row, int col, u8 index)
{
	int pixel = OFFSET(row, col, 240);
	int shortNumber = pixel/2;
	
	if(col %2)  // Is column odd?
	{
		// Yes
		videoBuffer[shortNumber] = (videoBuffer[shortNumber] & 0x00ff) |  (index<<8) ;
    }
    else
    {
        // No, it's even
		videoBuffer[shortNumber] = (videoBuffer[shortNumber] & 0xff00) |  (index) ;
	}
}

///////////////////////////////////////////////////////////////////////////////
//
// FlipPage could be implemented very mysteriously as
// REG_DISPCTL ^= BUFFER1FLAG;
// videoBuffer = (u16 *)((int)videoBuffer ^ 0xA000);
// However since we will start up displaying BUFFER 0
// We would need to initialize videoBuffer to BUFFER1
// The version below is clearer and will do the right thing!

void FlipPage()
{
	

	if(REG_DISPCTL & BUFFER1FLAG) // Are we displaying Buffer 1
	{
		// Yes
		REG_DISPCTL &= ~BUFFER1FLAG;  // Display Buffer 0
		videoBuffer = BUFFER1;		  // Point videoBuffer at off screen buffer
	}
	else
	{	
		// No
		REG_DISPCTL |= BUFFER1FLAG;   // Display Buffer 1
		videoBuffer = BUFFER0;        // Point videoBuffer at off screen buffer
	}
}

void fillScreen(u8 index)
{
	volatile u16 color = index<<8 | index;  // This must be volatile or the optimizer
											// won't bother to store the value
											// because it doesn't see where we are using
											// the variable
	DMA[3].src = &color;					// It doesn't realize we're passing the address
	DMA[3].dst = videoBuffer;				// to a DMA
	DMA[3].cnt = (38400/2)  | DMA_ON | DMA_SOURCE_FIXED;        
}
	

